package com.tmsb.bigscreen.service;


import com.tmsb.bigscreen.pojo.ActiveUser;
import com.tmsb.bigscreen.pojo.Number;
import com.tmsb.bigscreen.pojo.SalesDetailResult;
import com.tmsb.bigscreen.pojo.Style;
import com.tmsb.bigscreen.pojo.TitleItem;
import com.tmsb.bigscreen.utils.NumUtil;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.Tuple;

/**
 *Description:
 *Version:1.0.0
 *@author shihb
 *@date 2020/6/25 8:58
 */

@Service
public class BigScreenService {
  @Autowired
  private JedisCluster redisCluster;

//  @Autowired
//  private MallDao mallDao;
  private LinkedHashMap<String, String> cacheMap = new LinkedHashMap<String, String>(1000,1f,true) {
    int maxSize = 900;
    @Override
    protected boolean removeEldestEntry(Entry<String, String> eldest) {
      boolean flag=size() > 900;
      return flag;
    }
  };
  @Autowired
  private JdbcTemplate impala;
  private Map<String,String> shopTypeDict=new HashMap(10);;


  SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
  DecimalFormat df = new DecimalFormat("#.00");
  DecimalFormat df2 = new DecimalFormat("#");
  public List getSumList(){
    ArrayList<TitleItem> arr = new ArrayList<>();
    String nowDate = sdf.format(new Date());
    //今日销售额
    String momey = NumUtil.formatter(redisCluster.get("order:money:" + nowDate));
    //今日订单数
    String num = NumUtil.formatter(redisCluster.get("order:num:" + nowDate));
    // 今日活跃用户数
    String dau=NumUtil.formatter(redisCluster.hget("ucenter:dau",nowDate));
    //今日注册用户数
    String numberOfRegistrations=NumUtil.formatter(redisCluster.hget("ucenter:day:register",nowDate));
    //今日贡献值
    String score = redisCluster.hget("es:score:amount", nowDate);
    String numberOfScore=NumUtil.formatter(score==null?null:df2.format(Double.parseDouble(score)/10000));
    //折扣兑换绩效积分个数
    String amount = redisCluster.hget("taimu_main:user_stock_buy:amount", nowDate);
    String redeemPoints=NumUtil.formatter(amount==null?null:df.format(Double.parseDouble(amount)));
    //兑换绩效积分折扣金额
    String discount = redisCluster.hget("taimu_main:user_stock_buy:discount", nowDate);
    String discountAmount=NumUtil.formatter(discount==null?null:df.format(Double.parseDouble(discount)));
    //今日均价
    String averagePrice="";
    if(discount!=null && amount!=null){
      averagePrice = df.format(Double.parseDouble(discount) / Double.parseDouble(amount));
    }

    //今日释放绩效积分
    String avaAmount = redisCluster.hget("es:available:amount:", nowDate);
    String releasePoints =NumUtil.formatter(avaAmount==null?null:df.format(Double.parseDouble(avaAmount)));
    //今日用户体现金额
    String wdithdraw = NumUtil.formatter(redisCluster.hget("taimu_main:user_tixian:amount", nowDate));

    //泰木山泉每日订单件数
    String numberOfWaterOrders = NumUtil.formatter(redisCluster.hget("fair_shop:order_mall:sku_quantity", nowDate));

    //网点每日核销件数
    String numberOfWaterWriteOffs = NumUtil.formatter(redisCluster.hget("fair_shop:order_verified_network:verify_qty", nowDate));
    //网点每日进货件数
    String waterPurchaseNumber = NumUtil.formatter(redisCluster.hget("fair_shop:order_network:quantity", nowDate));



    String textAlign="left";
    Style style = new Style(22);
    arr.add(new TitleItem("今日销售额(元)",new Number(new ArrayList<String>(Collections.singleton(momey)),textAlign,"{nt}",style)));
    arr.add(new TitleItem("今日订单数",new Number(new ArrayList<String>(Collections.singleton(num)),textAlign,"{nt}",style)));
    arr.add(new TitleItem("今日释放绩效积分",new Number(new ArrayList<String>(Collections.singleton(releasePoints)),textAlign,"{nt}",style)));
    arr.add(new TitleItem("今日活跃用户数",new Number(new ArrayList<String>(Collections.singleton(dau)),textAlign,"{nt}",style)));
    arr.add(new TitleItem("今日提现金额(元)",new Number(new ArrayList<String>(Collections.singleton(wdithdraw)),textAlign,"{nt}",style)));
    arr.add(new TitleItem("今日注册用户数",new Number(new ArrayList<String>(Collections.singleton(numberOfRegistrations)),textAlign,"{nt}",style)));
    arr.add(new TitleItem("今日贡献值(万)",new Number(new ArrayList<String>(Collections.singleton(numberOfScore)),textAlign,"{nt}",style)));
    arr.add(new TitleItem("兑换绩效积分折扣金额",new Number(new ArrayList<String>(Collections.singleton(discountAmount)),textAlign,"{nt}",style)));
    arr.add(new TitleItem("今日均价",new Number(new ArrayList<String>(Collections.singleton(averagePrice)),textAlign,"{nt}",style)));
    arr.add(new TitleItem("折扣兑换绩效积分个数",new Number(new ArrayList<String>(Collections.singleton(redeemPoints)),textAlign,"{nt}",style)));
    arr.add(new TitleItem("今日山泉订单件数",new Number(new ArrayList<String>(Collections.singleton(numberOfWaterOrders)),textAlign,"{nt}",style)));
    arr.add(new TitleItem("今日水网点进货件数",new Number(new ArrayList<String>(Collections.singleton(waterPurchaseNumber)),textAlign,"{nt}",style)));
    arr.add(new TitleItem("今日水网点核销件数",new Number(new ArrayList<String>(Collections.singleton(numberOfWaterWriteOffs)),textAlign,"{nt}",style)));
    return arr;
  }
  public List getActiveUsers(){
    ArrayList<ActiveUser> arr = new ArrayList<>();
    String nowDate = sdf.format(new Date());
    Set<Tuple> set = redisCluster.zrevrangeWithScores("ucenter:provinces:dau:" + nowDate, 0,  - 1);
    set.forEach(o->{
      String name=o.getElement();
      arr.add(new ActiveUser(o.getElement().substring(o.getElement().indexOf("_")+1),df2.format(o.getScore())));
    });
    return arr;
  }
  public Map getHisSales(){
    System.out.println("getHisSales start");
    HashMap<String, List> map = new HashMap<>();
    try {
      ArrayList<String> datas = new ArrayList<>();
      ArrayList<String> dates = new ArrayList<>();
      String sql = "select the_date,pay_price from dm.d_mall_volume_count order by the_date";
      List<String[]> lists = impala.query(sql, (rs,i)->new String[]{rs.getString("the_date"),rs.getString("pay_price")});

      lists.forEach(row->{
        dates.add(row[0].toString().replace("-","/"));
        datas.add(row[1].toString());

      });
      map.put("data",datas);
      map.put("date",dates);
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("getHisSales over");
    return  map;
  }

  public List getTopGoods(int Cap) {
    ArrayList<Object> list = new ArrayList<>();
    String nowDate = sdf.format(new Date());
    Set<Tuple> set = redisCluster.zrevrangeWithScores("top:goods:" + nowDate, 0, Cap - 1);

//    for(Tuple tuple: tuples) {
//      System.out.println(tuple.getElement() + "-" + tuple.getScore());
//    }
    set.forEach(o->{
      ArrayList<String> item = new ArrayList<>();
      String id=o.getElement();
      String fullId="good"+id;
      String name=null;
      if(cacheMap.containsKey(fullId)){
        name=cacheMap.get(fullId);
      }else {
        String sql = "select title from mall.goods where id="+id;
        name=impala.queryForList(sql).get(0).get("title").toString();
//        name=mallDao.getGoodNameById(id);
        cacheMap.put(fullId,name);
      }
      item.add(id);
      item.add(name);
      item.add(df.format(o.getScore()));
      list.add(item);

    });
    return list;
  }

  public List getTopSellers(int Cap) {
    ArrayList<Object> list = new ArrayList<>();
    String nowDate = sdf.format(new Date());
    Set<Tuple> set = redisCluster.zrevrangeWithScores("top:sellers:" + nowDate, 0, Cap - 1);
    set.forEach(o->{
      ArrayList<String> item = new ArrayList<>();
      String id=o.getElement();
      String fullId="seller"+id;
      String name=null;
      if(cacheMap.containsKey(fullId)){
        name=cacheMap.get(fullId);
      }else {
        String sql = "select name from mall.shop where user_id="+id;
        name=impala.queryForList(sql).get(0).get("name").toString();
        cacheMap.put(fullId,name);
      }
      item.add(id);
      item.add(name);
      item.add(df.format(o.getScore()));
      list.add(item);

    });
    return list;
  }

  /**
   * 获取销售占比
   */
  public List getSalesDetails(){
    ArrayList<SalesDetailResult> list = new ArrayList<>();

    Map<String, String> map = redisCluster.hgetAll("shop.type.sum");
    map.forEach((k,v)->{
      if(!k.toLowerCase().startsWith("pre")){

        if(!shopTypeDict.containsKey(k)){
          updateShopTypeDict();
        }
        String name=shopTypeDict.get(k);
        list.add(new SalesDetailResult(name!=null?name:k,v));
      }
    });
    return list;
  }
  public void updateShopTypeDict(){
    String sql = "select dict_key, dict_val from dw.dict where catalog_id = 101";
    List<Map<String, Object>> maps = impala.queryForList(sql);
    maps.forEach(o->{
      String key = o.get("dict_key").toString();
      String value = o.get("dict_val").toString();
      shopTypeDict.put(key,value);
    });

  }

}
